<template>
  <div class="login">
    <div class="login_box">
      <div class="avatar_box"><img src="../assets/logo.png" alt="" /></div>
      <el-form ref="loginRef" :model="form" :rules="rules" label-width="0px">
        <!-- 用户名 -->
        <el-form-item prop="username" class="user">
          <el-input
            v-model="form.username"
            prefix-icon="el-icon-user-solid"
          ></el-input>
        </el-form-item>
        <!-- 密码 -->
        <el-form-item prop="password" class="password">
          <el-input
            v-model="form.password"
            type="password"
            prefix-icon="el-icon-view"
          ></el-input>
        </el-form-item>
        <!-- 按钮 -->
        <el-form-item class="btns">
          <el-button @click="login" type="primary">登录</el-button>
          <el-button @click="resetLogin" type="info">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<script>
export default {
  name: "Login",
  data() {
    return {
      form: {
        username: "admin",
        password: "123456",
      },
      rules: {
        username: [
          { required: true, message: "请输入您的用户名", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "长度在 3 到 10 个字符",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入您的登录密码", trigger: "blur" },
          {
            min: 6,
            max: 15,
            message: "长度在 6 到 15 个字符",
            trigger: "blur",
          },
        ],
      },
    };
  },
  methods: {
    //重置
    resetLogin() {
      this.form.name = "";
      this.form.password = "";
      // console.log(this.$refs.loginRef);
      // this.$refs.loginRef.resetField();
    },
    login() {
      this.$refs.loginRef.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$http.post("login", this.form);
        if (res.meta.status !== 200) return this.$message.error("登录失败");
        this.$message.success("登陆成功");
        //1.将登陆成功之后的token保存到客户端的sessionStorage中
        // console.log(res);
        window.sessionStorage.setItem("token", res.data.token);
        this.$router.push("/home");
      });
    },
  },
};
</script>
<style scoped>
.login {
  background-color: #2b4b6b;
  height: 100%;
}
.login_box {
  width: 450px;
  height: 300px;
  background-color: #fff;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}
.avatar_box {
  position: absolute;
  top: -50%;
  left: 50%;
  transform: translate(-50%, 50%);
  width: 130px;
  height: 130px;
  border-radius: 50%;
  padding: 10px;
  border: 1px solid #eee;
  box-shadow: 0 0 10px #ddd;
  background-color: #fff;
}
.avatar_box img {
  width: 100%;
  border-radius: 50%;
  background-color: #eee;
}
.btns {
  position: absolute;
  right: 20px;
}
.user {
  margin: 100px 20px 0;
}
.password {
  margin: 30px 20px 20px;
}
</style>